package com.qh.resourcehub.program.qzt.controller;

import com.qh.resourcehub.program.qzt.dto.QztCleanReadedDto;
import com.qh.resourcehub.program.qzt.dto.QztTodoDto;
import com.qh.resourcehub.program.qzt.service.QztTodoService;
import com.qh.resourcehub.program.qzt.vo.UserTodoDetailVO;
import com.qh.resourcehub.utils.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class QztTodoController {

    private static final Logger logger = LoggerFactory.getLogger(QztTodoController.class);

    @Autowired
    private QztTodoService qztTodoService;

    @Value("${qzt.sys.code:057003}")
    private String sysCode;

    @PostMapping("/cleanReaded")
    public Map<String, String> cleanReaded(@RequestBody QztCleanReadedDto cleanReadedDto) {
        Map<String, String> result = new HashMap<>();
        
        try {
            logger.info("收到气政通阅毕通知: sysCode={}, userCodes={}, businessId={}", 
                    cleanReadedDto.getSysCode(), cleanReadedDto.getUserCodes(), cleanReadedDto.getBusinessId());

            QztTodoDto todoDto = new QztTodoDto();
            todoDto.setSysCode(cleanReadedDto.getSysCode());
            todoDto.setModuleType(cleanReadedDto.getModuleType());
            todoDto.setRecType(cleanReadedDto.getRecType());
            todoDto.setUserCodes(cleanReadedDto.getUserCodes());
            todoDto.setBusinessId(cleanReadedDto.getBusinessId());
            todoDto.setTitle(cleanReadedDto.getTitle());
            todoDto.setContent(cleanReadedDto.getContent());
            todoDto.setSendTime(cleanReadedDto.getSendTime());
            todoDto.setStatus("03");
            todoDto.setSendName(cleanReadedDto.getSendName());
            todoDto.setSendCode(cleanReadedDto.getSendCode());
            todoDto.setDeptCode(cleanReadedDto.getDeptCode());
            todoDto.setOrgCode(cleanReadedDto.getOrgCode());
            todoDto.setPriority(0);

            String deleteResult = qztTodoService.deleteTodoFromQzt(todoDto);
            
            if ("success".equals(deleteResult)) {
                result.put("stateFlag", "01");
                logger.info("阅毕处理成功: businessId={}", cleanReadedDto.getBusinessId());
            } else {
                result.put("stateFlag", "02");
                result.put("msg", deleteResult);
                logger.warn("阅毕处理失败: businessId={}, result={}", cleanReadedDto.getBusinessId(), deleteResult);
            }
        } catch (Exception e) {
            logger.error("阅毕接口异常", e);
            result.put("stateFlag", "02");
            result.put("msg", e.getMessage());
        }
        
        return result;
    }

    @PostMapping("/syncTodos")
    public ApiResponse syncTodos() {
        try {
            qztTodoService.syncAllTodosToQzt();
            return ApiResponse.succeed("同步成功");
        } catch (Exception e) {
            logger.error("手动同步待办失败", e);
            return ApiResponse.succeedRequestErr("同步失败: " + e.getMessage());
        }
    }

    @PostMapping("/queryAllTodos")
    public ApiResponse queryAllTodos() {
        try {
            List<UserTodoDetailVO> todos = qztTodoService.queryAllUserTodos();
            return ApiResponse.succeed(todos);
        } catch (Exception e) {
            logger.error("查询所有待办失败", e);
            return ApiResponse.succeedRequestErr("查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/pushTodo")
    public ApiResponse pushTodo(@RequestBody QztTodoDto todoDto) {
        try {
            if (todoDto.getSysCode() == null || todoDto.getSysCode().isEmpty()) {
                todoDto.setSysCode(sysCode);
            }
            if (todoDto.getSendTime() == null || todoDto.getSendTime().isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                todoDto.setSendTime(sdf.format(new Date()));
            }
            
            String result = qztTodoService.pushTodoToQzt(todoDto);
            if ("success".equals(result)) {
                return ApiResponse.succeed("推送成功");
            } else {
                return ApiResponse.succeedRequestErr(result);
            }
        } catch (Exception e) {
            logger.error("推送待办失败", e);
            return ApiResponse.succeedRequestErr("推送失败: " + e.getMessage());
        }
    }

    @PostMapping("/deleteTodo")
    public ApiResponse deleteTodo(@RequestBody QztTodoDto todoDto) {
        try {
            if (todoDto.getSysCode() == null || todoDto.getSysCode().isEmpty()) {
                todoDto.setSysCode(sysCode);
            }
            if (todoDto.getSendTime() == null || todoDto.getSendTime().isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                todoDto.setSendTime(sdf.format(new Date()));
            }
            
            String result = qztTodoService.deleteTodoFromQzt(todoDto);
            if ("success".equals(result)) {
                return ApiResponse.succeed("删除成功");
            } else {
                return ApiResponse.succeedRequestErr(result);
            }
        } catch (Exception e) {
            logger.error("删除待办失败", e);
            return ApiResponse.succeedRequestErr("删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/testPushTodo")
    public ApiResponse testPushTodo() {
        try {
            QztTodoDto todoDto = new QztTodoDto();
            todoDto.setSysCode(sysCode);
            todoDto.setModuleType("01");
            todoDto.setRecType("01");
            todoDto.setDeptCode("001057018008");
            todoDto.setOrgCode("001057018");
            todoDto.setUserCodes("ef398a80-fac6-430e-92aa-a15fddc2f218");
            todoDto.setBusinessId("TEST-BUS-20250119-003");
            todoDto.setTitle("测试待办-" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            todoDto.setContent("这是一条测试待办数据");
            todoDto.setLink("http://10.181.23.237/index.html#/inventoryManagement/list/Home?userCode=ef398a80-fac6-430e-92aa-a15fddc2f218");
            todoDto.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            todoDto.setStatus("01");
            todoDto.setPriority(0);

            String result = qztTodoService.pushTodoToQzt(todoDto);
            if ("success".equals(result)) {
                return ApiResponse.succeed("测试推送成功");
            } else {
                return ApiResponse.succeedRequestErr(result);
            }
        } catch (Exception e) {
            logger.error("测试推送待办失败", e);
            return ApiResponse.succeedRequestErr("测试推送失败: " + e.getMessage());
        }
    }
}
